package com.xyy.saas.payment.adpater.yop;

import com.xyy.saas.payment.common.Constants;
import com.xyy.saas.payment.common.exception.PaymentException;
import com.xyy.saas.payment.cores.enums.ResultCodeEnum;
import com.xyy.saas.payment.util.JSONUtils;
import com.yeepay.yop.sdk.exception.YopClientException;
import com.yeepay.yop.sdk.service.account.AccountClient;
import com.yeepay.yop.sdk.service.account.AccountClientBuilder;
import com.yeepay.yop.sdk.service.account.model.AccountinfosQueryAccountDTOResult;
import com.yeepay.yop.sdk.service.account.model.AccountinfosQueryQueryAccountInfoListRespDTOResult;
import com.yeepay.yop.sdk.service.account.request.AccountinfosQueryRequest;
import com.yeepay.yop.sdk.service.account.response.AccountinfosQueryResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

/**
 * 资金账户余额查询
 */
@Service
@Slf4j
public class YopBalanceQueryV2 {
    private final AccountClient api = AccountClientBuilder.builder().build();

    /**
     * 全部账户余额查询
     */
    public List<AccountinfosQueryAccountDTOResult> balanceQueryV2(AccountinfosQueryRequest param) throws PaymentException {
        log.info("YopBalanceQueryV2#balanceQueryV2 param:{}", JSONUtils.toJSON(param));

        try {
            AccountinfosQueryResponse response = api.accountinfosQuery(param);
            log.info("YopBalanceQueryV2#balanceQueryV2 request:{} response:{}", JSONUtils.toJSON(param), JSONUtils.toJSON(response));
            AccountinfosQueryQueryAccountInfoListRespDTOResult result = response.getResult();

            if(!Constants.YOP_SUCCESS_CODE.equals(result.getReturnCode())) {
                throw new PaymentException(result.getReturnCode(), result.getReturnMsg());
            }

            return result.getAccountInfoList();
        }
        catch(Exception ex) {
            log.error("YopBalanceQueryV2#balanceQueryV2 error, param=" + JSONUtils.toJSON(param) + ", errorMsg=" + ex.getMessage() ,ex);

            if(ex instanceof PaymentException) {
                throw ex;
            }
            else if(ex instanceof YopClientException) {
                throw new PaymentException(ResultCodeEnum.YOP_SYSTEM_ERROR.getCode(), ex.getMessage());
            }

            throw new PaymentException(ResultCodeEnum.YOP_SYSTEM_ERROR);
        }
    }
}
